package com.geline.word.controller;

import com.geline.extension.domain.Result;
import com.geline.word.starter.SdkWordService;
import com.geline.word.util.WordContent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;

/**
 * word上传下载
 * @author: mengxin
 * @date: 2022/10/18 16:58
 */
@Slf4j
public abstract class AbstractWordController {

    @Autowired(required = false)
    private SdkWordService sdkWordService;

    //处理生成的html文件
    protected abstract WordContent handleUploadFile(String id, File htmlFile);

    /**
     * 查询 html内容
     * @param id
     * @return
     */
    protected abstract WordContent getWordContent(String id);

    /**
     * 删除一条记录
     * @param id
     * @return
     */
    protected abstract boolean deleteById(String id);

    /**
     * 上传word文件并转为html
     * localhost:8080/upload/{id}
     * @param id     关联ID
     * @param multipartFile   word文件流
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/upload/{id}")
    public Result upload(@PathVariable String id, @RequestParam("file") MultipartFile multipartFile) throws Exception {
        File htmlFile = sdkWordService.uploadWord2Html(id, multipartFile);
        if(htmlFile != null){
            WordContent bean = this.handleUploadFile(id, htmlFile);
            return Result.ok(bean);
        }else {
            return Result.fail("上传解析失败！");
        }
    }

    /**
     * 读取html生成并下载word文件
     * GET: localhost:8080/export/{id}
     * @param id
     * @param request
     * @param response
     * @throws Exception
     */
    @GetMapping(value = "/export/{id}")
    public void export(@PathVariable String id, HttpServletRequest request, HttpServletResponse response) throws Exception {
        WordContent wordContent = getWordContent(id);
        sdkWordService.downDocxByHtml(wordContent.getFileName(), wordContent.getContent(), request, response);
    }

    /**
     * 查询word预览地址
     * GET: localhost:8080/getPreviewUrl/{id}
     * @param id
     * @return
     */
    @GetMapping(value = "/getPreviewUrl/{id}")
    public Result getPreviewUrl(@PathVariable String id) {
        String previewUrl = sdkWordService.getPreviewUrl(id);
        return Result.ok(previewUrl);
    }

    /**
     * 删除一条记录，同时删除上传的资料文件
     * DELETE: localhost:8080/delete/{id}
     * @param id
     * @return
     */
    @DeleteMapping(value = "/delete/{id}")
    public Result delete(@PathVariable String id) {
        boolean b = this.deleteById(id);
        if(b){
            sdkWordService.deleteUploadFile(id);
            return Result.ok();
        }
        return Result.fail("删除失败！");
    }
}
